<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input
            placeholder="请输入用户名"
            v-model="queryinfo.query"
            size="small"
            class="input-with-select"
          >
            <el-button slot="append" icon="el-icon-search" @click="query()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" icon="el-icon-search" size="small" @click="gosave()">添加</el-button>
        </el-col>
      </el-row>

      <el-row>
        <el-table class="tabletop" :data="tableData" border style="width: 100%">
          <el-table-column type="index" label="序号"></el-table-column>
          <el-table-column prop="username" label="用户名" width="180"></el-table-column>
          <el-table-column prop="email" label="邮箱地址"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.mg_state" @change="changeUserState(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="198">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="goeait(scope.row)"></el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="del(scope.row)"></el-button>
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-s-tools"
                @click="gosetrole(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryinfo.pagesize"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalsize"
        ></el-pagination>
      </el-row>
    </el-card>

    <!-- 用户模态窗开始 -->
    <el-dialog title="用户信息维护" :visible.sync="isShow" :close-on-click-modal="false">
      <el-form
        :model="saveobj"
        :rules="checkForm"
        ref="saveForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="saveobj.username" :disabled="iseait"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!iseait">
          <el-input v-model="saveobj.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="saveobj.email"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="mobile">
          <el-input v-model="saveobj.mobile"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="save()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 用户模态窗结束 -->

    <!-- 分配角色的模态窗开始 -->
    <el-dialog title="分配角色" :visible.sync="roleShow" :close-on-click-modal="false">
      <el-form :model="setroleobj">
        <el-form-item label="用户名:">{{setroleobj.username}}</el-form-item>
        <el-form-item label="当前角色:">{{setroleobj.role_name}}</el-form-item>
        <el-form-item label="活动区域">
          <el-select v-model="setroleobj.rid" placeholder="请选择角色">
            <el-option
              v-for="(item) in rolelist"
              :label="item.roleName"
              :value="item.id"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="roleShow = false">取 消</el-button>
        <el-button type="primary" @click="setrole()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色的模态窗结束 -->
  </div>
</template>

<script>
export default {
  name: "users",
  data() {
    return {
      //与角色弹窗中的数据形成数据双向绑定
      setroleobj: {
        id: 0,
        rid: "",
        role_name: "", //当前角色名称
        username: "" //当前用户名
      },
      roleShow: false, //该属性用于控制角色分配弹窗是否显示
      rolelist: [], //该属性用于记录角色列表
      iseait: false, //设置是否禁用输入框,和是否显示密码输入框
      queryinfo: {
        query: "",
        pagenum: 1,
        pagesize: 5
      },
      totalsize: 0, //记录总数据条数
      isShow: false, //控制模态窗的显示与隐藏
      tableData: null,
      //定义表单数据的双向数据绑定
      saveobj: {
        id: 0,
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      //定义验证规则
      checkForm: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 6, max: 10, message: "长度在 6到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        email: [{ required: true, message: "请输入邮箱账号", trigger: "blur" }],
        mobile: [{ required: true, message: "请输入联系方式", trigger: "blur" }]
      }
    };
  },
  methods: {
    // 实现分配角色的功能
    async setrole() {
      // 判断是否选择了新的角色
     if (this.setroleobj.rid) {
      //  发送数据请求到后台接口
      let rst = await this.$http.put(`users/${this.setroleobj.id}/role`, {
          rid: this.setroleobj.rid
        });
        if (rst.meta.status == 200) {
          // 当角色修改成功则调用query方法
          this.query();
          // 关闭模态窗
          this.roleShow=false;
          // 提示分配成功
          this.$message.success("角色分配成功");
        } else {
          this.$message.error("角色分配失败");
        }
      } else {
        this.$message.error("请选择新的角色");
      }
    },
    // 当点击分配角色时触发的方法
    gosetrole(obj) {
      let { id, role_name, username } = obj;
      // 为用户名和当前角色名赋值
      this.setroleobj.role_name = role_name;
      this.setroleobj.username = username;
      this.setroleobj.id=id;
      // 打开弹窗
      this.roleShow = true;
    },

    async getrolelist() {
      let rst = await this.$http.get("roles");
      if (rst.meta.status == 200) {
        //将所有的角色信息赋值给rolelist属性
        this.rolelist = rst.data;
      } else {
        this.$message.error("获取角色失败");
      }
    },

    //定义修改用户状态的方法
    async changeUserState(obj) {
      let rst = await this.$http.put(`users/${obj.id}/state/${obj.mg_state}`);
      if (rst.meta.status != 200) {
        this.$message.error("状态修改失败");
      }
    },

    // 定义点击修改按钮时触发的方法
    async goeait(obj) {
      //当点击修改按钮时发送一个数据请求根据id查询单个用户信息
      let rst = await this.$http.get(`users/${obj.id}`);
      if (rst.meta.status == 200) {
        //设置输入框禁用
        this.iseait = true;
        // 打开弹窗
        this.isShow = true;
        // 将结果赋值给saveobj的email属性和mobile属性
        this.saveobj.email = rst.data.email;
        this.saveobj.mobile = rst.data.mobile;
        this.saveobj.username = rst.data.username;
        this.saveobj.id = rst.data.id;
      } else {
        this.$message.error("获取数据失败");
      }
    },
    //定义del方法用于根据id删除一个用户信息
    del(obj) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          //当点击确认时需要执行的代码块
          let rst = await this.$http.delete(`users\/${obj.id}`);
          if (rst.meta.status == 200) {
            //当后台响应状态码为200时则表示删除成功
            //调用查询方法
            this.query();
          } else {
            // 当删除失败时提示删除失败
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    //定义save方法,用于保存数据
    save() {
      // 通过总验证规则
      this.$refs.saveForm.validate(async valid => {
        if (valid) {
          let rst = null;
          //根据id判断,当id的值不等于0时则执行修改操作,当id的值为0时则执行添加操作
          if (this.saveobj.id != 0) {
            // 发送修改的数据请求
            rst = await this.$http.put(
              `users\/${this.saveobj.id}`,
              this.saveobj
            );
          } else {
            // 发送添加的数据请求
            rst = await this.$http.post("users", this.saveobj);
          }
          if (rst.meta.status == 201 || rst.meta.status == 200) {
            this.$message.success("保存成功");
            this.query(); //添加成功后需要刷新列表信息
            this.isShow = false; //关闭弹窗
          } else {
            this.$message.error("添加失败");
          }
        } else {
          this.$message.error("请输入合法的添加数据");
          return false;
        }
      });
    },

    async query() {
      let rst = await this.$http.get("users", this.queryinfo);
      this.tableData = rst.data.users;
      this.totalsize = rst.data.total; //获取总数据条数
    },
    gosave() {
      this.isShow = true;
      this.iseait = false;
      this.saveobj = {
        id: 0,
        username: "",
        password: "",
        email: "",
        mobile: ""
      };
    },
    // 当每页显示的数据条数发生变化时调用的方法,该方法接收一个参数,值为当前每页显示的数据条数
    handleSizeChange(size) {
      this.queryinfo.pagesize = size;
      this.query();
    },
    // 当点击页码时触发的方法,该方法接收一个参数,参数表示当前页码
    handleCurrentChange(pagenum) {
      this.queryinfo.pagenum = pagenum;
      this.query();
    }
  },
  mounted() {
    this.query();
    this.getrolelist();
  }
};
</script>

<style>
</style>
